﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

namespace SkyReader
{
    public partial class Download : PhoneApplicationPage
    {
        private string bookContent;
        public Download()
        {
            InitializeComponent();

            this.webBrowser.Navigating += new EventHandler<NavigatingEventArgs>(webBrowser_Navigating);
            this.webBrowser.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(webBrowser_Navigated);

            this.webBrowser.LoadCompleted += new System.Windows.Navigation.LoadCompletedEventHandler(webBrowser_LoadCompleted);
            this.BackKeyPress += new EventHandler<System.ComponentModel.CancelEventArgs>(Download_BackKeyPress);

            this.lstFontSize.SelectedIndex = 2;
            this.lstFontFamily.SelectedIndex = 7;
        }


      

        private void webBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            // show save panel
            if (Regex.IsMatch(e.Uri.AbsoluteUri, @"^https://\w{1,50}.\w{1,50}.livefilestore.com/")
               && e.Uri.AbsoluteUri.IndexOf("login.aspx", StringComparison.CurrentCultureIgnoreCase) == -1)
            {
                // Get book title
                string title;
                int lastIndex = fileName.LastIndexOf('.');
                title = fileName.Substring(0, lastIndex);
                this.txtTitle.Text = title;

                // Get book content
                bookContent = this.webBrowser.SaveToString();
                int startIndex = 32;
                lastIndex = bookContent.LastIndexOf("</PRE></BODY></HTML>");
                bookContent = bookContent.Substring(startIndex, lastIndex - startIndex);
                this.lblPreview.Text = string.Format("{0} ...", bookContent.Substring(0, 35));

                this.lblPreview.FontFamily = new System.Windows.Media.FontFamily(this.lstFontFamily.SelectedItem.ToString());
                this.lblPreview.FontSize = Convert.ToDouble(this.lstFontSize.SelectedItem);

                LoadPanel.Visibility = System.Windows.Visibility.Collapsed;
                SavePanel.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private string fileName = string.Empty;
        private string folderUri = string.Empty;
        private void webBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.Uri.AbsoluteUri.Contains("browse.aspx"))
            {
                this.folderUri = e.Uri.AbsoluteUri;
            }

            if (e.Uri.AbsoluteUri.Contains("self.aspx"))
            {
                System.Threading.Thread.Sleep(2000);

                string htmlContent = this.webBrowser.SaveToString();
                int startIndex = htmlContent.IndexOf("<TITLE>") + 7;
                int lastIndex = htmlContent.IndexOf(" - Windows Live</TITLE>", startIndex);
                if (lastIndex != -1)
                {
                    fileName = htmlContent.Substring(startIndex, lastIndex - startIndex);
                }
            }

            LoadPanel.Visibility = System.Windows.Visibility.Collapsed;
            ContentPanel.Visibility = System.Windows.Visibility.Visible;


            // Beacuse web control need to take some time load content of text after download book, system show load panel and hide web control
            if (Regex.IsMatch(e.Uri.AbsoluteUri, @"^https://\w{1,50}.\w{1,50}.livefilestore.com/")
              && e.Uri.AbsoluteUri.IndexOf("login.aspx", StringComparison.CurrentCultureIgnoreCase) == -1)
            {
                LoadPanel.Visibility = System.Windows.Visibility.Visible;
                ContentPanel.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void webBrowser_Navigating(object sender, NavigatingEventArgs e)
        {
            if (Regex.IsMatch(e.Uri.AbsoluteUri, @"^https://\w{1,50}.\w{1,50}.livefilestore.com/")
                && e.Uri.AbsoluteUri.IndexOf("login.aspx", StringComparison.CurrentCultureIgnoreCase) == -1)
            {
                if (this.fileName.EndsWith(".txt", StringComparison.CurrentCultureIgnoreCase) == false)
                {
                    MessageBox.Show("The file format is not supported. The book must be a plain text or HTML file.", "Incorrect file format", MessageBoxButton.OK);
                    e.Cancel = true;
                    return;
                }
                lblLoading.Text = "Downloading...";
            }
            else
            {
                lblLoading.Text = "Loading...";
            }

            LoadPanel.Visibility = System.Windows.Visibility.Visible;
            ContentPanel.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void Homebutton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Bookshelf.xaml", UriKind.Relative));
        }

        private string bookId;
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            bookId = "BOOK" + this.txtTitle.Text.Trim();
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            if (settings.Contains(bookId))
            {
                MessageBoxResult result = MessageBox.Show("There is already a book with the same title in the book shelf, are you sure you want to replace this book?", "Replace book?", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.Cancel)
                {
                    return;
                }
            }

            // show waiting for 
            SavePanel.Visibility = System.Windows.Visibility.Collapsed;
            LoadPanel.Visibility = System.Windows.Visibility.Visible;
            lblLoading.Text = "Saving and creating page index ...";
            
            Deployment.Current.Dispatcher.BeginInvoke(SaveBook); 
        }

        private void SaveBook()
        {
            //progBar.IsIndeterminate = false;

            Book book = null;
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            if (settings.Contains(bookId))
            {
                book = settings[bookId] as Book;
            }
            else
            {
                book = book = new Book()
                {
                    Title = this.txtTitle.Text.Trim(),
                    FileName = string.Format("{0}.txt", Guid.NewGuid()),
                    CurrentPage =1,
                    MarkList = new List<Mark>()
                };
            }

            settings[bookId] = book;
            settings.Save();
            // 2. save book into iso folder 
            IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication();
            if (isoFile.FileExists(book.FileName))
            {
                isoFile.DeleteFile(book.FileName);
            }

            using (IsolatedStorageFileStream isoFs = isoFile.CreateFile(book.FileName))
            {
                byte[] content = Encoding.UTF8.GetBytes(bookContent);
                isoFs.Write(content, 0, content.Length);
                book.DateCreated = DateTime.Now;
                book.Size = string.Format("{0:N} KB", content.Length / 1024);
            }

            // 3. generate page index of the book
            book.PageDict = new Dictionary<int, int>();
            book.FontSize = Convert.ToDouble(this.lstFontSize.SelectedItem.ToString());
            book.FontFamily = this.lstFontFamily.SelectedItem.ToString();

            string overflowContent = string.Empty;
            int point = 0;
            int pagePoint = 0;
            int currentPage = 0;

            TextBlock textBlock = new TextBlock()
            {
                TextWrapping = TextWrapping.Wrap,
                FontSize = book.FontSize,
                FontFamily = new FontFamily(book.FontFamily),
                Width = SystemConst.PAGE_WIDTH,
                Height = SystemConst.PAGE_HIGHT
            };

            

            PageBuilder page = new PageBuilder(textBlock);
            while (point != bookContent.Length)
            {
                string line = string.Empty;
                if (overflowContent.Length == 0)
                {
                    if (point + 100 < bookContent.Length)
                    {
                        line = bookContent.Substring(point, 100);
                    }
                    else
                    {
                        line = bookContent.Substring(point);
                    }

                    point = point + 100;
                    if (point > bookContent.Length)
                    {
                        point = bookContent.Length;
                    }
                }
                else
                {
                    line = overflowContent;
                }

                overflowContent = page.Append(line);
                if (overflowContent.Length != 0)
                {
                    currentPage = currentPage + 1;
                    book.PageDict.Add(currentPage, pagePoint);
                    pagePoint = pagePoint + page.Content.Length;
                    page = new PageBuilder(textBlock);
                }
            }
            currentPage = currentPage + 1;
            book.PageDict.Add(currentPage, pagePoint);

            //progBar.IsIndeterminate = true;

            MessageBox.Show("This book has been added to the book shelf.", "Save successful", MessageBoxButton.OK);

            LoadPanel.Visibility = System.Windows.Visibility.Collapsed;
            this.webBrowser.Navigate(new Uri(this.folderUri, UriKind.Absolute));
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            ContentPanel.Visibility = System.Windows.Visibility.Visible;
            SavePanel.Visibility = System.Windows.Visibility.Collapsed;

            this.webBrowser.Navigate(new Uri("http://skydrive.live.com", UriKind.Absolute));
        }

        private void Download_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {

        }

        private void lstFontSize_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.lblPreview != null)
            {
                ListPicker listPicker = sender as ListPicker;
                this.lblPreview.FontSize = Convert.ToDouble(listPicker.SelectedItem.ToString());
            }
        }

        private void lstFontFamily_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.lblPreview != null)
            {
                ListPicker listPicker = sender as ListPicker;
                this.lblPreview.FontFamily = new FontFamily(listPicker.SelectedItem.ToString());
            }
        }


    }
}